package mysql

import (
	"bluebell/models"
	"crypto/md5"
	"database/sql"
	"encoding/hex"
)

const secret = "www.kxy.com"

// CheckUserExit 检查指定用户名的用户是否存在
func CheckUserExit(username string) (err error) {
	sqlstr := "select count(id) from user where username = ?"
	var count int
	if err := db.Get(&count, sqlstr, username); err != nil {
		return err
	}
	if count > 0 {
		return ErrorUserExist
	}
	return
}

// InsertUser 向数据库中插入一条新的用户
func InsertUser(user *models.User) (err error) {
	// 对密码进行加密
	user.Password = encryptPassword(user.Password)
	// 插入数据库
	sqlstr := "Insert into user(user_id, username, password) values(?, ?, ?)"
	_, err = db.Exec(sqlstr, user.UserID, user.Username, user.Password)
	return
}

func Login(user *models.User) (err error) {
	user.Password = encryptPassword(user.Password)
	sqlstr := "SELECT password FROM user WHERE username = ?"
	var password string
	if err := db.Get(&password, sqlstr, user.Username); err == sql.ErrNoRows {
		return ErrorUserNotExist
	} else if err != nil {
		return err
	}

	if password != user.Password {
		return ErrorInvalidPassword
	}
	return
}

func encryptPassword(oPassword string) string {
	h := md5.New()
	h.Write([]byte(secret))
	return hex.EncodeToString(h.Sum([]byte(oPassword)))
}

// GetUserByID 根据ID获取用户信息
func GetUserByID(id int64) (user *models.User, err error) {
	user = new(models.User)
	sqlstr := "select user_id, username from user where user_id = ?"
	err = db.Get(user, sqlstr, id)
	return
}

func GetUserIdByName(username string) (int64, error) {
	sqlstr := "select user_id from user where username = ?"
	var user_id int64
	err := db.Get(&user_id, sqlstr, username)
	return user_id, err
}
